<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>7-pie</title>
    <!-- <script src="./js/d3.min.js"></script> -->
    <!-- <script src="https://d3js.org/d3.v4.min.js"></script> -->
    <script src="http://d3js.org/d3.v4.min.js" charset="utf-8"></script>
</head>
<style>
    .arc text {
        font: 12px arial;
        text-anchor: middle;
    }

    .arc path {
        stroke: #fff;
    }

    .title {
        fill: green;
        font-weight: italic;
    }
</style>

<body>
    <svg width="400" height="400"></svg>
</body>
<script>
    var svg = d3.select("svg"),
        width = svg.attr("width"),
        height = svg.attr("height"),
        radius = Math.min(width, height) / 2;

    var g = svg.append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    var color = d3.scaleOrdinal(['gray', 'green', 'brown', 'orange']);

    var pie = d3.pie()
        .value(function (d) { return d.percent; });

    // 修改path的innerRadius 内圈边距 0表示无边距 -> 饼图     有边距即为甜甜圈图
    var path = d3.arc()
        .outerRadius(radius - 10)
        .innerRadius(100);

    var arc = d3.arc()
        .outerRadius(radius)
        .innerRadius(0);

    var label = d3
        .arc()
        .outerRadius(radius)
        .innerRadius(radius - 80);

    d3.csv("populations.csv", function (error, data) {
        if (error) {
            throw error;
        }
        console.log(data)
        data = [
            { states: "UP", percent: 50 },
            { states: "Maharastra", percent: 60 },
            { states: "Bihar", percent: 40 },
            { states: "MP", percent: 20 },
            { states: "Gujarat", percent: 70 },
            { states: "WB", percent: 80 },
            { states: "TW", percent: 40 }
        ]
        console.log(data)
        var arc = g.selectAll(".arc")
            .data(pie(data))
            .enter()
            .append("g")
            .attr("class", "arc");

        arc.append("path")
            .attr("d", path)
            .attr("fill", function (d) {
                return color(d.data.states);
            });

        arc.append("text")
            .attr("transform", function (d) {
                return "translate(" + label.centroid(d) + ")";
            })
            .text(function (d) {
                return d.data.states;
            });
    });

    svg.append("g")
        .attr("transform", "translate(" + (width / 2 - 120) + "," + 20 + ")")
        .append("text")
        .text("Top population states in india")
        .attr("class", "title")
</script>

</html>